package com.gitee.wsl.doc.prosemirror.model.fragment.ext

import com.gitee.wsl.doc.prosemirror.model.fragment.Fragment
import com.gitee.wsl.doc.prosemirror.model.fragment.Slice
import com.gitee.wsl.doc.prosemirror.model.node.Node


fun Fragment.closeFragment( depth: Int, oldOpen: Int, newOpen: Int, parent: Node? = null): Fragment {
    var fragment = this
    if (depth < oldOpen) {
        val first = fragment.firstChild!!
        fragment = fragment.replaceChild(
            0,
            first.copy(first.content.closeFragment( depth + 1, oldOpen, newOpen, first))
        )
    }
    if (depth > newOpen) {
        val match = parent!!.contentMatchAt(0)
        val start = match.fillBefore(fragment)!!.append(fragment)
        fragment = start.append(match.matchFragment(start)!!.fillBefore(Fragment.empty, true)!!)
    }
    return fragment
}

fun Fragment.closeRange( side: Int, from: Int, to: Int, depth: Int, openEnd: Int):Fragment {
    val fragment = this
    val node = if(side < 0)  fragment.firstChild else fragment.lastChild
    var inner: Fragment = node!!.content
    var openEnd = openEnd
    if (fragment.childCount > 1)
        openEnd = 0
    if (depth < to - 1)
        inner = inner.closeRange( side, from, to, depth + 1, openEnd)
    if (depth >= from)
        inner = if(side < 0)
                   node.contentMatchAt(0).fillBefore(inner, openEnd <= depth)!!.append(inner)
                else
                    inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)!!)
    return fragment.replaceChild(if(side < 0) 0 else fragment.childCount - 1, node.copy(inner))
}

fun Slice.closeSlice( openStart: Int, openEnd: Int):Slice {
    var slice = this
    if (openStart < slice.openStart)
        slice = Slice(slice.content.closeRange( -1, openStart, slice.openStart, 0, slice.openEnd), openStart, slice.openEnd)
    if (openEnd < slice.openEnd)
        slice = Slice(slice.content.closeRange( 1, openEnd, slice.openEnd, 0, 0), slice.openStart, openEnd)
    return slice
}